package com.wang.remotecontrolview.slice;

import com.wang.remotecontrolview.ResourceTable;
import com.wang.remotecontrolview.utils.ScreenUtils;
import com.wang.remotecontrolview.widget.DraggableButton;
import com.wang.remotecontrolview_ohos.RemoteControlView;
import com.wang.remotecontrolview_ohos.util.PhoneUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainAbilitySlice extends AbilitySlice {

    private final static HiLogLabel LABEL = new HiLogLabel(3, 0x00201, "MainAbilitySlice");

    private RemoteControlView mRemoteControlView;
    private Text mTextControlDes;

    private StackLayout mRootLayout;
    private PageSlider mPageSlider;
    private RadioContainer mRadioContainer;

    private Point point, componentPo;

    private List<Component> mPageViews = new ArrayList<>();
    //添加成功与否的Map
    private Map<String, Boolean> mBtnStatusMap = new HashMap<>();
    //
    private Map<Component, Point> mBtnAddMap = new HashMap<>();

    //pageOneId
    private int[] mPageOneId = new int[]{ResourceTable.Id_button_close, ResourceTable.Id_button_home,
            ResourceTable.Id_button_exit, ResourceTable.Id_button_back,
            ResourceTable.Id_button_setting, ResourceTable.Id_button_source,
            ResourceTable.Id_button_text, ResourceTable.Id_button_menu,
            ResourceTable.Id_button_out, ResourceTable.Id_button_mute};
    //pageTwoId
    private int[] mPageTwoId = new int[]{ResourceTable.Id_button_cursor, ResourceTable.Id_button_channel,
            ResourceTable.Id_button_vol, ResourceTable.Id_button_random, ResourceTable.Id_button_playLoop,};
    //pageThreeId
    private int[] mPageThreeId = new int[]{ResourceTable.Id_button_play, ResourceTable.Id_button_stop,
            ResourceTable.Id_button_pause, ResourceTable.Id_button_pause2,
            ResourceTable.Id_button_previous, ResourceTable.Id_button_next,
            ResourceTable.Id_button_backward, ResourceTable.Id_button_forward,
            ResourceTable.Id_button_height, ResourceTable.Id_button_width};
    //pageFourId
    private int[] mPageFourId = new int[]{ResourceTable.Id_button_0, ResourceTable.Id_button_1,
            ResourceTable.Id_button_2, ResourceTable.Id_button_3,
            ResourceTable.Id_button_4, ResourceTable.Id_button_5,
            ResourceTable.Id_button_6, ResourceTable.Id_button_7,
            ResourceTable.Id_button_8, ResourceTable.Id_button_9};

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        mBtnAddMap.clear();
        // 提示文字
        Text mTextView = new Text(getContext());
        mTextView.setTextSize(1000, Text.TextSizeType.VP);
        mTextView.setTextColor(Color.RED);
        mTextView.setText("长按并拖拽下方按钮到这里");

        mRemoteControlView = (RemoteControlView) findComponentById(ResourceTable.Id_remote_control);
        mTextControlDes = (Text) findComponentById(ResourceTable.Id_control_describe);

        mRootLayout = (StackLayout) findComponentById(ResourceTable.Id_root_layout);
        mPageSlider = (PageSlider) findComponentById(ResourceTable.Id_pager_slider);
        mRadioContainer = (RadioContainer) findComponentById(ResourceTable.Id_radio_container);
        ((RadioButton) mRadioContainer.getComponentAt(0)).setChecked(true);


        initPagerViews();
    }

    private void initPagerViews() {
        LayoutScatter layoutScatter = LayoutScatter.getInstance(getContext());
        TableLayout dependentLayout1 = (TableLayout) layoutScatter.parse(ResourceTable.Layout_pageSlider1, null, false);
        DirectionalLayout dependentLayout2 = (DirectionalLayout) layoutScatter.parse(ResourceTable.Layout_pageSlider2, null, false);
        TableLayout dependentLayout3 = (TableLayout) layoutScatter.parse(ResourceTable.Layout_pageSlider3, null, false);
        TableLayout dependentLayout4 = (TableLayout) layoutScatter.parse(ResourceTable.Layout_pageSlider4, null, false);

        mPageViews.add(dependentLayout1);
        mPageViews.add(dependentLayout2);
        mPageViews.add(dependentLayout3);
        mPageViews.add(dependentLayout4);


        mPageSlider.setProvider(new PageSliderProvider() {
            @Override
            public int getCount() {
                return mPageViews.size();
            }

            @Override
            public Object createPageInContainer(ComponentContainer componentContainer, int i) {
                componentContainer.addComponent(mPageViews.get(i));
                return mPageViews.get(i);
            }

            @Override
            public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
                (componentContainer).removeComponent(mPageViews.get(i));
            }

            @Override
            public boolean isPageMatchToObject(Component component, Object o) {
                return component == o;
            }
        });

        mPageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {

            }

            @Override
            public void onPageSlideStateChanged(int i) {

            }

            @Override
            public void onPageChosen(int i) {
                ((RadioButton) mRadioContainer.getComponentAt(i)).setChecked(true);
            }
        });

        initClick(dependentLayout1, dependentLayout2, dependentLayout3, dependentLayout4);
    }

    private void initClick(TableLayout dependentLayout1, DirectionalLayout dependentLayout2, TableLayout dependentLayout3, TableLayout dependentLayout4) {
        initArrays(1, mPageOneId, dependentLayout1);
        initArrays(2, mPageTwoId, dependentLayout2);
        initArrays(3, mPageThreeId, dependentLayout3);
        initArrays(4, mPageFourId, dependentLayout4);

    }

    private void initArrays(int currentPager, int[] arrays, ComponentContainer container) {
        if (currentPager == 2) {
            for (int i = 0; i < arrays.length; i++) {
                setBtnClick(container, arrays[i], 0, 0, i == 4 ? 1 : 0);
            }
        } else {
            for (int i = 0; i < arrays.length; i++) {
                setBtnClick(container, arrays[i], 1, i >= 5 ? (i % 5) : i, i >= 5 ? 1 : 0);
            }
        }
    }

    private void setBtnClick(ComponentContainer container, int resID, int pageIndex, int columnIndex, int rowIndex) {
        DraggableButton button = (DraggableButton) container.findComponentById(resID);
        button.setTag(resID);


        button.setLongClickedListener(component -> {
            if (pageIndex == 1) {
                int btnMarginLeft = getBtnMarginLeft(button, 3);
                int space = button.getWidth() + btnMarginLeft;
                int btnMarginTop = getBtnMarginTop(button, 3);

                doCopyPagerOneButton(btnMarginLeft, btnMarginTop, space, button, columnIndex, rowIndex);
            } else {
                doCopyPagerTwoButton(container, resID, button, columnIndex, rowIndex);
            }
        });
    }

    private void initDragListeners(DraggableButton button) {
        button.setDraggedListener(Component.DRAG_HORIZONTAL_VERTICAL, new Component.DraggedListener() {
            @Override
            public void onDragDown(Component component, DragInfo dragInfo) {
                HiLog.debug(LABEL, "%{public}%s", "onDragDown");
            }

            @Override
            public void onDragStart(Component component, DragInfo dragInfo) {
                HiLog.debug(LABEL, "%{public}%s", "onDragStart");
                point = dragInfo.startPoint;
                componentPo = new Point(component.getContentPositionX(), component.getContentPositionY());
                //表示有多次移动的同一目标，则需要将之前的状态清除
                if (checkRepeatDrag(component)) {
                    mBtnAddMap.remove(component);
                }
            }

            @Override
            public void onDragUpdate(Component component, DragInfo dragInfo) {
                HiLog.debug(LABEL, "%{public}%s", "onDragUpdate");
                float xOffset = dragInfo.updatePoint.getPointX() - point.getPointX();

                float yOffset = dragInfo.updatePoint.getPointY() - point.getPointY();

                //setContentPosition为组件在父组件中的位置
                component.setContentPosition(componentPo.getPointX() + xOffset, componentPo.getPointY() + yOffset);
                componentPo = new Point(component.getContentPositionX(), component.getContentPositionY());
            }

            @Override
            public void onDragEnd(Component component, DragInfo dragInfo) {
                //如果不是覆盖则添加上去
                boolean b = checkOverView(component, point);
                System.out.println("覆盖-" + "b -->" + b);

                System.out.println("checkOverBoundary(component) -->" + checkOverBoundary(component));
                if (checkOverBoundary(component) && b) {
                    System.out.println("onDrag----if");
                    mBtnAddMap.put(component, point);
                } else {
                    System.out.println("onDrag----else");
                    mBtnAddMap.remove(component);
                    mRootLayout.removeComponent(component);
                }
                System.out.println("onDragEnd" + "mBtnAddMap.size() = " + mBtnAddMap.size());
                if (mBtnAddMap.isEmpty()) {
                    mTextControlDes.setVisibility(Component.VISIBLE);
                } else {
                    mTextControlDes.setVisibility(Component.HIDE);
                }
            }

            @Override
            public void onDragCancel(Component component, DragInfo dragInfo) {
                HiLog.debug(LABEL, "%{public}%s", "onDragCancel");
            }
        });
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void doCopyPagerOneButton(int marginLeft, int marginTop, int space, DraggableButton btn, int columnIndex, int rowIndex) {
        ComponentContainer.LayoutConfig layoutConfig = btn.getLayoutConfig();
        layoutConfig.setMarginLeft(marginLeft + space * columnIndex);
        layoutConfig.setMarginTop(marginTop + space * rowIndex);

        DraggableButton button = new DraggableButton(btn.getContext());

        button.setAroundElementsRelative(btn.getStartElement(), null, null, null);

        /**设置文字*/
        if (btn.getText() != null) {
            button.setText(btn.getText());
            button.setTextColor(btn.getTextColor());
            button.setTextSize(btn.getTextSize());
            button.setTextAlignment(btn.getTextAlignment());
        }
        //button.setComponentPosition(componentPosition);
        /**设置图片居中*/
        button.setPaddingRight(btn.getPaddingRight());
        button.setPaddingLeft(btn.getPaddingLeft());
        button.setPaddingTop(btn.getPaddingTop());
        button.setPaddingBottom(btn.getPaddingBottom());
        button.setHeight(layoutConfig.height);
        button.setWidth(layoutConfig.width);
        button.setBackground(btn.getBackgroundElement());
        button.setLayoutConfig(layoutConfig);
        button.setTag(btn.getTag().toString());
        mRootLayout.addComponent(button);
        mBtnStatusMap.put(btn.getTag().toString(), false);
        initDragListeners(button);
    }

    /**
     * 判断是否是二次移动同一目标
     */
    private boolean checkRepeatDrag(Component component) {
        if (mBtnAddMap.isEmpty()) {
            return false;
        }
        String s = component.getTag().toString();
        for (Component c : mBtnAddMap.keySet()) {
            String sTag = c.getTag().toString();
            if (sTag.equals(s)) {
                return true;
            }
        }
        return false;
    }

    private void doCopyPagerTwoButton(ComponentContainer container, int resID, DraggableButton btn, int columnIndex, int rowIndex) {
        ComponentContainer.LayoutConfig layoutConfig = btn.getLayoutConfig();

        switch (resID) {
            case ResourceTable.Id_button_cursor:
                layoutConfig.setMarginTop(getBtnPagerTwoMarginTop(container, ResourceTable.Id_button_cursor, 6));
                layoutConfig.setMarginLeft(getBtnPagerTwoMarginLeft(container, ResourceTable.Id_button_cursor, -24));
                break;
            case ResourceTable.Id_button_channel:
                layoutConfig.setMarginTop(getBtnPagerTwoMarginTop(container, ResourceTable.Id_button_channel, -6));
                layoutConfig.setMarginLeft(getBtnPagerTwoMarginLeft(container, ResourceTable.Id_button_channel, -24));
                break;
            case ResourceTable.Id_button_vol:
                layoutConfig.setMarginTop(getBtnPagerTwoMarginTop(container, ResourceTable.Id_button_vol, -6));
                layoutConfig.setMarginLeft(getBtnPagerTwoMarginLeft(container, ResourceTable.Id_button_vol, -2));
                break;
            case ResourceTable.Id_button_random:
                layoutConfig.setMarginTop(getBtnPagerTwoMarginTop(container, ResourceTable.Id_button_random, 6));
                layoutConfig.setMarginLeft(getBtnPagerTwoMarginLeft(container, ResourceTable.Id_button_random, 26));
                break;
            case ResourceTable.Id_button_playLoop:
                layoutConfig.setMarginTop(getBtnPagerTwoMarginTop(container, ResourceTable.Id_button_playLoop, 24));
                layoutConfig.setMarginLeft(getBtnPagerTwoMarginLeft(container, ResourceTable.Id_button_playLoop, 26));
                break;
        }
        DraggableButton button = new DraggableButton(btn.getContext());
        if (btn.getForegroundElement() != null) {
            button.setForeground(btn.getForegroundElement());
        } else {
            button.setAroundElementsRelative(btn.getStartElement(), null, null, null);
        }
        /**设置图片居中*/
        button.setMarginLeft(btn.getMarginLeft());
        button.setMarginBottom(btn.getMarginBottom());
        button.setPaddingLeft(btn.getPaddingLeft());
        button.setPaddingRight(btn.getPaddingRight());
        button.setHeight(layoutConfig.height);
        button.setWidth(layoutConfig.width);
        button.setBackground(btn.getBackgroundElement());
        button.setTag(btn.getTag().toString());
        button.setLayoutConfig(layoutConfig);
        mRootLayout.addComponent(button);
        System.out.println("pagerTwo-" + "btn.getTag() = " + btn.getTag().toString());
        mBtnStatusMap.put(btn.getTag().toString(), false);
        initDragListeners(button);
    }

    private boolean isNotOverView;

    /**
     * 判断是否重叠
     */
    private boolean checkOverView(Component component, Point point) {
        isNotOverView = false;
        int newWidth = component.getWidth();//132
        int newHeight = component.getHeight();//330
        if (mBtnAddMap.isEmpty()) {
            return true;
        }
        System.out.println("newWidth = " + newWidth + " newHeight = " + newHeight);
        float newPointX = component.getContentPositionX();//316
        float newPointY = component.getContentPositionY();//594
        System.out.println("newPointX = " + newPointX + " newPointY = " + newPointY);
        //所落在的位置
        float newAddWidthPointX = newPointX + newWidth;//448
        float newAddHeightPointY = newPointY + newHeight;//646
        System.out.println("newAddWidthPointX = " + newAddWidthPointX + " newAddHeightPointY = " + newAddHeightPointY);
        for (Component c : mBtnAddMap.keySet()) {
            int oldWidth = c.getWidth();
            int oldHeight = c.getHeight();
            System.out.println("-----------------------");
            System.out.println("oldWidth = " + oldWidth + " oldHeight = " + oldHeight);
            float oldPointX = c.getContentPositionX();//316
            float oldPointY = c.getContentPositionY();
            System.out.println("oldPointX = " + oldPointX + " oldPointY = " + oldPointY);
            float w = c.getContentPositionX() + oldWidth;
            float h = c.getContentPositionY() + oldHeight;
            System.out.println("w = " + w + " h = " + h);
            //循环完成只要发现一个有覆盖则return
            if (newAddWidthPointX < oldPointX || newPointX > w) {
                isNotOverView = true;
            } else if (newAddHeightPointY < oldPointY || newPointY > h) {
                isNotOverView = true;
            } else {
                return false;
            }
        }
        return isNotOverView;
    }

    /**
     * 判断是否越边界
     */
    private boolean checkOverBoundary(Component component) {
        //上边界
        int leftX = PhoneUtils.getInstance().getStartX();
        int rightX = PhoneUtils.getInstance().getEndX();
        int topY = PhoneUtils.getInstance().getTopY();
        int bottomY = PhoneUtils.getInstance().getBottomY();
        int width = component.getWidth();
        int height = component.getHeight();
        float pointX = component.getContentPositionX();//316
        float pointY = component.getContentPositionY();//594
        float addWidthPointX = pointX + width;//448
        float addHeightPointY = pointY + height;//646
        System.out.println("pointX = " + pointX + " leftX = " + leftX + " addWidthPointX = " + addWidthPointX + " rightX = " + rightX);
        System.out.println("pointY = " + pointY + " topY = " + topY + " addHeightPointY = " + addHeightPointY + " bottomY = " + bottomY);
        if (pointX > leftX && addWidthPointX < rightX && pointY > topY && addHeightPointY < bottomY) {
            return true;
        }
        return false;
    }

    private int getBtnMarginLeft(DraggableButton button, int offset) {
        int screenWidth = ScreenUtils.getScreenWidth(getContext());
        int marginLeft = (screenWidth - button.getWidth() * 5) / 6 + offset;
        return marginLeft;
    }

    private int getBtnMarginTop(DraggableButton button, int offset) {
        int height = mRemoteControlView.getHeight();
        int space = (mPageSlider.getHeight() - button.getHeight() * 2) / 3 + offset;
        return height + space;
    }

    private int getBtnPagerTwoMarginTop(ComponentContainer container, int resID, int offset) {
        int marginTop = 0;
        int buttonCursorHeight = container.findComponentById(ResourceTable.Id_button_cursor).getHeight();
        int buttonChannelHeight = container.findComponentById(ResourceTable.Id_button_channel).getHeight();
        int buttonVolHeight = container.findComponentById(ResourceTable.Id_button_vol).getHeight();
        int buttonRandomHeight = container.findComponentById(ResourceTable.Id_button_random).getHeight();
        int height = mRemoteControlView.getHeight();
        switch (resID) {
            case ResourceTable.Id_button_cursor:
                marginTop = height + (mPageSlider.getHeight() - buttonCursorHeight) / 2 + offset;
                break;
            case ResourceTable.Id_button_channel:
                marginTop = height + (mPageSlider.getHeight() - buttonChannelHeight) / 2 + offset;
                break;
            case ResourceTable.Id_button_vol:
                marginTop = height + (mPageSlider.getHeight() - buttonVolHeight) / 2 + offset;
                break;
            case ResourceTable.Id_button_random:
                int space = (mPageSlider.getHeight() - buttonRandomHeight * 2) / 3;
                marginTop = height + space + offset;
                break;
            case ResourceTable.Id_button_playLoop:
                int space1 = (mPageSlider.getHeight() - buttonRandomHeight * 2) / 3;
                marginTop = height + space1 * 2 + buttonRandomHeight + offset;
                break;
        }
        return marginTop;
    }

    private int getBtnPagerTwoMarginLeft(ComponentContainer container, int resID, int offset) {
        int marginLeft = 0;
        int buttonCursorWidth = container.findComponentById(ResourceTable.Id_button_cursor).getWidth();
        int buttonChannelWidth = container.findComponentById(ResourceTable.Id_button_channel).getWidth();
        int buttonVolWidth = container.findComponentById(ResourceTable.Id_button_vol).getWidth();
        int buttonRandomWidth = container.findComponentById(ResourceTable.Id_button_random).getWidth();
        int screenWidth = ScreenUtils.getScreenWidth(getContext());
        int space = (screenWidth - buttonCursorWidth - buttonChannelWidth - buttonVolWidth - buttonRandomWidth) / 5;

        switch (resID) {
            case ResourceTable.Id_button_cursor:
                marginLeft = space + offset;
                break;
            case ResourceTable.Id_button_channel:
                marginLeft = space * 2 + buttonCursorWidth + offset;
                break;
            case ResourceTable.Id_button_vol:
                marginLeft = space * 3 + buttonCursorWidth + buttonChannelWidth + +offset;
                break;
            case ResourceTable.Id_button_random:
            case ResourceTable.Id_button_playLoop:
                marginLeft = space * 4 + buttonCursorWidth + buttonChannelWidth + buttonVolWidth + offset;
                break;
        }
        return marginLeft;
    }
}
